package com.iecas.handler;

import cn.hutool.log.StaticLog;
import cn.hutool.socket.nio.ChannelHandler;
import com.iecas.enums.BizEnum;
import com.iecas.launch.Client;
import com.iecas.request.Root;
import com.iecas.utils.RequestUtils;
import lombok.Data;

import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

@Data
public class DefaultClientChannelHandler implements ChannelHandler {

    Client client;

    public DefaultClientChannelHandler(Client client) {
        this.client = client;
    }

    @Override
    public void handle(SocketChannel socketChannel) throws Exception {
        try {
            ByteBuffer byteBuffer = ByteBuffer.allocate(4);
            int read = socketChannel.read(byteBuffer);
            if (read > 0) {
                byteBuffer.flip();
                int dataSize = byteBuffer.getInt();
                byte[] expectBytes = RequestUtils.getExpectBytes(socketChannel, dataSize);
                Root baseRes = RequestUtils.decode(expectBytes);
                BizEnum bizEnum = BizEnum.getByCode(baseRes.getCode());
                BaseHandler handler = bizEnum.getHandler();
                handler.handle(baseRes, null, client, socketChannel);
            }
        } catch (Exception e) {
            e.printStackTrace();
            socketChannel.close();
        }
    }
}
